<template>
  <div class="wrapper">
    <Row>
      <Col span="4" style="height: 100%">
        <Card class="article-category mr_10">
          <Tree :data="treeData" @on-select-change="handleCateChange"></Tree>
        </Card>
      </Col>
      <Col span="20">
        <Card class="article-detail">
          <Row @keydown.enter.native="handleSearch">
            <Form
                ref="searchForm"
                :label-width="70"
                :model="searchForm"
                class="search-form"
                inline
                style="width: 100%"
            >
              <Form-item label="文章標題" prop="title">
                <Input
                    v-model="searchForm.title"
                    clearable
                    placeholder="請輸入文章標題"
                    style="width: 200px"
                    type="text"
                />
              </Form-item>
              <Button
                  class="search-btn"
                  icon="ios-search"
                  type="primary"
                  @click="handleSearch"
              >搜索
              </Button
              >
            </Form>
          </Row>
          <Row class="operation padding-row">
            <Button v-if="!selected" type="primary" @click="add">添加</Button>
          </Row>
          <Table
              ref="table"
              :columns="columns"
              :data="data"
              :loading="loading"
              border
          >
            <!-- 頁面展示 -->
            <template slot="openStatusSlot" slot-scope="scope">
              <div></div>
              <i-switch
                  v-model="scope.row.openStatus"
                  size="large"
                  @on-change="changeSwitch(scope.row)"
              >
                <span slot="open">展示</span>
                <span slot="close">隐藏</span>
              </i-switch>
            </template>
          </Table>
          <Row class="mt_10" justify="end" type="flex">
            <Page
                :current="searchForm.pageNumber"
                :page-size="searchForm.pageSize"
                :page-size-opts="[10, 20, 50]"
                :total="total"
                show-elevator
                show-total
                size="small"
                @on-change="changePage"
                @on-page-size-change="changePageSize"
            >
            </Page>
          </Row>
        </Card>
      </Col>
    </Row>
    <template v-if="!selected">
      <Modal
          v-model="modalVisible"
          :mask-closable="false"
          :title="modalTitle"
          :width="1100"
      >
        <Form ref="form" :label-width="100" :model="form">
          <FormItem label="文章標題" prop="title">
            <Input v-model="form.title" clearable style="width: 40%"/>
          </FormItem>
          <FormItem label="文章分類" prop="categoryId">
            <Select
                v-model="treeValue"
                clearable
                placeholder="請選擇"
                style="width: 180px"
            >
              <Option v-if="treeValue" :value="treeValue" style="display: none"
              >{{ treeValue }}
              </Option>
              <Tree
                  :data="treeDataDefault"
                  @on-select-change="handleCheckChange"
              ></Tree>
            </Select>
          </FormItem>
          <FormItem label="文章排序" prop="sort">
            <Input
                v-model="form.sort"
                clearable
                style="width: 10%"
                type="number"
            />
          </FormItem>
          <FormItem class="form-item-view-el" label="文章内容" prop="content">
<!--            <tinymec-->
<!--                v-if="modalVisible"-->
<!--                ref="editor"-->
<!--                v-model="form.content"-->
<!--                openXss-->
<!--            ></tinymec>-->
<!--            <Input-->
<!--              v-model="form.content"-->
<!--              style="width: 50%; height: 200px"-->
<!--              type=textarea-->
<!--            />-->
            <div class="layui-input-block custom-textarea-container" :class="{ 'hover': isHovered }" @mouseover="handleMouseOver" @mouseout="handleMouseOut">
            <textarea
              v-model="form.content"
              style="width: 50%; height: 200px"
              class="layui-textarea custom-textarea"
              ></textarea>
            </div>
          </FormItem>
          <FormItem label="是否展示" prop="openStatus">
            <i-switch v-model="form.openStatus" size="large">
              <span slot="open">展示</span>
              <span slot="close">隐藏</span>
            </i-switch>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="modalVisible = false">取消</Button>
          <Button :loading="submitLoading" type="primary" @click="handleSubmit"
          >提交
          </Button
          >
        </div>
      </Modal>
    </template>
  </div>
</template>

<script>
import {
  delArticle,
  getArticle,
  getArticleCategory,
  saveArticle,
  seeArticle,
  updateArticle,
  updateArticleStatus,
} from "@/api/pages";
import tinymec from "@/components/editor/index.vue";

export default {
  components: {
    tinymec: tinymec,
  },
  props: {
    selected: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      clearContent() {
        this.form.content = '';
      },
      isHovered: false,
      selectedIndex: 99999, // 已選下標
      loading: true, // 表單加载狀態
      modalType: 0, // 添加或编辑標识
      modalVisible: false, // 添加或编辑显示
      modalTitle: "", // 添加或编辑標題
      treeDataDefault: [],
      searchForm: {
        // 搜索框初始化对象
        pageNumber: 1, // 当前頁數
        pageSize: 10, // 頁面大小
        sort: "createTime", // 默认排序字段
        order: "desc", // 默认排序方式
        categoryId: "",
      },
      searchTreeValue: "", // 切换
      form: {
        // 添加或编辑表單对象初始化數据
        openStatus: false,
        title: "",
        categoryId: "",
        sort: 1,
        content: "",
        id: "",
      },
      list: [], // 列表
      treeValue: "", // 選擇的分類
      //树结构
      treeData: [],
      submitLoading: false, // 添加或编辑提交狀態
      columns: [
        // 表頭
        {
          title: "分類名稱",
          key: "articleCategoryName",
          width: 150,
        },
        {
          title: "文章標題",
          key: "title",
          minWidth: 200,
          tooltip: true,
        },
        {
          title: "是否显示",
          key: "openStatus",
          width: 100,
          slot: "openStatusSlot",
        },
        {
          title: "排序",
          key: "sort",
          width: 100,
        },
        {
          title: "操作",
          key: "action",
          align: "center",

          width: 230,
          render: (h, params) => {
            return h("div", [
              h(
                  "Button",
                  {
                    props: {
                      size: "small",
                      type:
                          this.selectedIndex == params.index
                              ? "primary"
                              : "default",
                    },
                    style: {
                      marginRight: "5px",
                      display: this.selected ? "" : "none",
                    },
                    on: {
                      click: () => {
                        this.selectedIndex = params.index;
                        this.$emit("callbacked", params.row);
                      },
                    },
                  },
                  this.selectedIndex == params.index ? "已選" : "選擇"
              ),
              h(
                  "Button",
                  {
                    props: {
                      size: "small",
                      type: "info",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.edit(params.row);
                      },
                    },
                  },
                  "编辑"
              ),
              h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small",
                    },
                    on: {
                      click: () => {
                        this.remove(params.row);
                      },
                    },
                  },
                  "删除"
              ),
            ]);
          },
        },
      ],
      data: [], // 表單數据
      total: 0, // 表單數据总數
    };
  },
  watch: {
    "searchForm.categoryId": {
      handler() {
        this.handleSearch();
      },
      deep: true,
    },
    "searchForm.title": {
      handler() {
        this.handleSearch();
      },
      deep: true,
    },
  },
  methods: {
    handleMouseOver() {
      this.isHovered = true;
    },
    handleMouseOut() {
      this.isHovered = false;
    },
    // 初始化數据
    init() {
      this.getDataList();
      this.getAllList(0);
    },
    // 選擇分類回调
    handleCateChange(data) {
      let {value, title} = data[0];
      this.list.push({
        value,
        title,
      });
      this.searchForm.categoryId = value;
      this.searchTreeValue = title;
    },
    //是否展示文章
    changeSwitch(v) {
      let params = {
        status: v.openStatus,
      };
      updateArticleStatus(v.id, params).then((res) => {
        this.submitLoading = false;
        if (res.success) {
        }
      });
    },
    // 文章分類的選擇事件
    handleCheckChange(data) {
      let value = "";
      let title = "";
      this.list = [];
      data.forEach((item, index) => {
        value += `${item.value},`;
        title += `${item.title},`;
      });
      value = value.substring(0, value.length - 1);
      title = title.substring(0, title.length - 1);
      this.list.push({
        value,
        title,
      });
      this.form.categoryId = value;
      this.treeValue = title;
    },
    // 改变頁數
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getDataList();
    },
    // 改变頁碼
    changePageSize(v) {
      this.selected.pageNumber = 1;
      this.searchForm.pageSize = v;
      this.getDataList();
    },
    // 搜索列表
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getDataList();
    },
    // 获取全部文章分類
    getAllList(parent_id) {
      this.loading = true;
      getArticleCategory(parent_id).then((res) => {
        this.loading = false;
        if (res.success) {
          this.treeData = this.getTree(res.result);
          this.treeDataDefault = this.getTree(res.result);
          this.treeData.unshift({
            title: "全部",
            level: 0,
            children: [],
            id: "0",
            categoryId: 0,
          });
        }
      });
    },
    // 文章分類格式化方法
    getTree(tree = []) {
      let arr = [];
      if (!!tree && tree.length !== 0) {
        tree.forEach((item) => {
          let obj = {};
          obj.title = item.articleCategoryName;
          obj.value = item.id;
          obj.attr = item.articleCategoryName; // 其他你想要添加的属性
          obj.expand = false;
          obj.selected = false;
          obj.children = this.getTree(item.children); // 递归调用
          arr.push(obj);
        });
      }
      return arr;
    },
    // 获取文章列表
    getDataList(val) {
      if (val) this.form = {};
      this.loading = true;
      getArticle(this.searchForm).then((res) => {
        this.loading = false;
        if (res.success) {
          this.total = res.result.total;
          //为了在是否展示一列展示开关 需要改一下數据類型，最终提交再次更改
          this.data = [];
          if (res.result.records.length > 0) {
            this.data = res.result.records;
          }
        }
      });
      this.total = this.data?.length;
      this.loading = false;
    },
    // 添加文章
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          if (this.modalType === 0) {
            // 添加 避免编辑後傳入id等數据 記得删除
            delete this.form.id;
            saveArticle(this.form).then((res) => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getDataList();
                this.modalVisible = false;
              }
            });
          } else {
            // 编辑
            updateArticle(this.form).then((res) => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getDataList();
                this.modalVisible = false;
              }
            });
          }
        }
      });
    },
    // 添加文章modal
    add() {
      this.modalType = 0;
      this.modalTitle = "添加文章";
      this.treeValue = "";

      this.form = {
        sort: 1,
        content: "",
      };
      this.$refs.form.resetFields();
      delete this.form.id;
      this.modalVisible = true;
    },
    // 编辑文章modal
    edit(data) {
      this.modalType = 1;
      this.modalTitle = "编辑文章";
      this.treeValue = "";
      this.form = {
        content: "",
      };
      this.$refs.form.resetFields();

      seeArticle(data.id).then((res) => {
        if (res.result) {
          this.modalVisible = true;
          this.form.categoryId = res.result.categoryId;
          this.treeValue = data.articleCategoryName;
          this.form.id = data.id;
          this.form.content = res.result.content;
          this.form.title = res.result.title;
          this.form.sort = res.result.sort;
          this.form.openStatus = res.result.openStatus;
        }
      });
    },
    // 删除文章
    remove(v) {
      this.$Modal.confirm({
        title: "確認删除",
        content: "您確認要删除么?",
        loading: true,
        onOk: () => {
          // 删除
          delArticle(v.id).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.getDataList();
            }
          });
        },
      });
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<style>
.custom-textarea-container {
  position: relative;
}
.custom-textarea {
  border-radius: 8px;
  background-color: #f9f9f9;
  padding: 10px;
  border: 1px solid #ddd;
  transition: border-color 0.3s;
}
.custom-textarea-container.hover .custom-textarea {
  border-color: red;
}
.clear-button {
  position: absolute;
  top: 10px;
  right: 10px;
  border: none;
  background: none;
  color: red;
  cursor: pointer;
  font-size: 16px;
}

.input_text{
  max-width: 100%;
  height: 500px;
  min-height: 50px;
  vertical-align: bottom;
  font-size: 12px;
}
</style>
